﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Kokomo.Environment.Commanding;
using System.Collections.Specialized;
using System.Windows.Input;

namespace Kokomo.Environment.Hosting
{
	class RecentDocumentMenuViewModel : MenuItemViewModel
	{
		public ICommand OpenDocumentCommand { get; private set; }

		public RecentDocumentMenuViewModel(
			ICommand openDocumentCommand,
			IEnumerable<RecentDocumentEntry> entries
			)
		{
			if (openDocumentCommand == null) throw new ArgumentNullException("openDocumentCommand");
			if (entries == null) throw new ArgumentNullException("entries");

			this.OpenDocumentCommand = openDocumentCommand;
			this.Entries = entries;
			INotifyCollectionChanged notifyCollection = entries as INotifyCollectionChanged;
			if (notifyCollection != null)
			{
				notifyCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Entries_CollectionChanged);
			}
			this.RefreshEntries();
		}

		public override UiString Text
		{
			get { return UiString.FromString(Messages.RecentMenuTitle); }
		}

		void Entries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			RefreshEntries();
		}

		private void RefreshEntries()
		{
			this._items = this.Entries.Select(this.CreateMenuItemForEntry);
			this.OnPropertyChanged("Items");
		}
		private RecentDocumentMenuItemViewModel CreateMenuItemForEntry(RecentDocumentEntry entry)
		{
			return new RecentDocumentMenuItemViewModel(entry, this.OpenDocumentCommand);
		}

		public IEnumerable<RecentDocumentEntry> Entries { get; private set; }

		private IEnumerable<MenuItemViewModel> _items;
		public override IEnumerable<MenuItemViewModel> Items
		{
			get
			{
				return this._items;
			}
		}
	}
}